<template>
  <div>
    <van-field v-model="tranIcon.address" label="账号" placeholder="请输入地址" />
    <van-field v-model="tranIcon.balance" label="money" placeholder="请输入money" type="number" />
    <button @click="giveMoney">转账</button>
    <div>当前用户</div>
    <div>当前地址：{{ nowInfo.address }}</div>
    <div>当前钱包余额{{ nowInfo.balance }}MTK</div>
  </div>
</template>

<script setup>
import { ethers, formatEther, parseUnits } from 'ethers';
import { reactive } from 'vue';

// 合约的 ABI
const tokenAbi = [
  // 省略其他方法，只保留示例用到的函数
  'function name() external view returns (string)',
  'function symbol() external view returns (string)',
  'function decimals() external view returns (uint8)',
  'function totalSupply() external view returns (uint256)',
  'function balanceOf(address account) external view returns (uint256)',
  'function transfer(address recipient, uint256 amount) external returns (bool)',
  'function mint(uint256 amount) external',
  'function burn() external'
];

// 合约地址
const tokenAddress = '0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0';
let provider = null;
let signer = ref(null);
let myTokenContract = ref(null);

const tranIcon = reactive({
  address: '',
  balance: ''
});
const nowInfo = reactive({
  address: '',
  balance: ''
});
// 连接到以太坊网络（使用 MetaMask 的 provider）

async function main() {
  provider = new ethers.BrowserProvider(window.ethereum);
  const accounts = await provider.listAccounts();
  console.log('accounts', accounts);
  // 请求用户授权
  await provider.send('eth_requestAccounts', []);

  // 获取用户的签名者（signer）
  signer = await provider.getSigner();

  // 创建合约实例
  myTokenContract = new ethers.Contract(tokenAddress, tokenAbi, signer);
  console.log(provide, signer, myTokenContract);
  // 调用合约的方法
  try {
    const totalSupply = await myTokenContract.totalSupply();

    nowInfo.address = await signer.address;
    nowInfo.balance = formatEther(await myTokenContract.balanceOf(nowInfo.address));
    console.log('Your Balance:', nowInfo.balance.toString());
    // 转账示例
    // 替换为接收者地址
    // const amountToSend = ethers.utils.parseUnits('10', 18); // 转账 10 MTK
    // const tx = await myTokenContract.transfer(recipientAddress, ONE_GWEI);
    // console.log('Transfer Transaction:', tx);
  } catch (error) {
    console.error('Error:', error);
  }
}

async function giveMoney() {
  console.log(tranIcon);
  const money = parseUnits(tranIcon.balance, 18);
  const tx = await myTokenContract.transfer(tranIcon.address, money, {
    gasLimit: 100000 // 提高 Gas Limit
  });
  console.log('Transfer Transaction:', tx);
}

main();
</script>

<style lang="scss" scoped></style>
